/*
 * @Author: lokei
 * @Date: 2022-11-11 20:55:39
 * @LastEditors: lokei
 * @LastEditTime: 2023-10-25 00:00:21
 * @Description: 
 */
package cn.lokei.task.handler.douyin;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@Configuration
@PropertySource(value = { "file:conf/db.properties" })
public class SyncOrderHandler {

    @Value("${debug.on:0}")
    private String debug_on;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void handler(MapRecord<String, String, String> record) {
        if (debug_on.equals("1")) {
            log.info("发送抖音订单同步：" + record.toString());
        }
        String pid = record.getValue().get("pid");
        Object douyin_info = redisTemplate.opsForValue().get("proj:" + pid + ":douyin");
        if (douyin_info != null) {
            JSONObject douyin_info_json = JSONObject.parseObject(douyin_info.toString());
            String access_token_key = "douyin_access_token" + "_" + douyin_info_json.getString("appid");
            RestTemplate template = new RestTemplate();
            String access_token = (String) redisTemplate.opsForValue().get(access_token_key);
            if (access_token == null) {
                try {
                    String url = "https://developer.toutiao.com/api/apps/v2/token";
                    Map<String, Object> requestMap = new HashMap<>();
                    // JSONObject requestMap = new JSONObject();
                    requestMap.put("grant_type", "client_credential");
                    requestMap.put("appid", douyin_info_json.getString("appid"));
                    requestMap.put("secret", douyin_info_json.getString("secret"));

                    ResponseEntity<JSONObject> result = template.postForEntity(url, requestMap, JSONObject.class);

                    HttpStatus statusCode = result.getStatusCode(); // 获取响应码
                    if (debug_on.equals("1")) {
                        log.info("获取抖音access_token状态：" + statusCode.toString());
                    }
                    if (statusCode == HttpStatus.OK) {
                        JSONObject body = result.getBody();
                        if (debug_on.equals("1")) {
                            if (body != null) {
                                log.info("获取抖音access_token Body：" + body.toString());
                            } else {
                                log.info("获取抖音access_token Body：获取NULL");
                            }

                        }
                        Integer err_no = body.getInteger("err_no");
                        if (err_no == 0) {
                            JSONObject data = body.getJSONObject("data");
                            access_token = data.getString("access_token");
                            Integer expires_in = data.getInteger("expires_in") - 5 * 60;
                            redisTemplate.opsForValue().set(access_token_key, access_token,
                                    expires_in,
                                    TimeUnit.SECONDS);
                        }
                    } else {
                        log.error("saas 服务访问失败！");
                        // throw new RuntimeException("saas 服务访问失败！");
                    }
                } catch (Exception e) {
                    log.error(e.toString());
                    // throw new RuntimeException(e.toString());
                }
            }
            if (access_token != null) {
                // Template template = templateDao.queryAll()
                String url = "https://developer.toutiao.com/api/apps/order/v2/push";
                Map<String, Object> requestMap = new HashMap<>();
                requestMap.put("access_token", access_token);
                requestMap.put("app_name", "douyin");
                requestMap.put("open_id", record.getValue().get("open_id"));
                requestMap.put("order_detail", record.getValue().get("order_detail"));
                requestMap.put("order_status", Integer.valueOf(record.getValue().get("order_status")));
                requestMap.put("order_type", Integer.valueOf(record.getValue().get("order_type")));
                Date now = new Date();
                requestMap.put("update_time", now.getTime());
                ResponseEntity<JSONObject> result = template.postForEntity(url, requestMap, JSONObject.class);
                if (debug_on.equals("1")) {
                    log.info("抖音订单同步结果：" + result.toString());
                }
            }
        }
    }
}
